Copied from upstream:
https://hg.mozilla.org/releases/mozilla-esr38/raw-rev/185b233ea03f

# HG changeset patch
# User Henri Sivonen <hsivonen@hsivonen.fi>
# Date 1455100746 -7200
# Node ID 185b233ea03f3811404e3979b65ec86b29d13555
# Parent  271e3a5a53d96871141e89271f611033b512e3e4
Bug 1246014. r=wchen. a=sylvestre

diff --git a/parser/html/javasrc/TreeBuilder.java b/parser/html/javasrc/TreeBuilder.java
--- a/parser/html/javasrc/TreeBuilder.java
+++ b/parser/html/javasrc/TreeBuilder.java
@@ -4437,17 +4437,17 @@ public abstract class TreeBuilder<T> imp
         return TreeBuilder.NOT_FOUND_ON_STACK;
     }
 
     private void clearStackBackTo(int eltPos) throws SAXException {
         int eltGroup = stack[eltPos].getGroup();
         while (currentPtr > eltPos) { // > not >= intentional
             if (stack[currentPtr].ns == "http://www.w3.org/1999/xhtml"
                     && stack[currentPtr].getGroup() == TEMPLATE
-                    && (eltGroup == TABLE || eltGroup == TBODY_OR_THEAD_OR_TFOOT|| eltGroup == TR || eltGroup == HTML)) {
+                    && (eltGroup == TABLE || eltGroup == TBODY_OR_THEAD_OR_TFOOT|| eltGroup == TR || eltPos == 0)) {
                 return;
             }
             pop();
         }
     }
 
     private void resetTheInsertionMode() {
         StackNode<T> node;
diff --git a/parser/html/nsHtml5TreeBuilder.cpp b/parser/html/nsHtml5TreeBuilder.cpp
--- a/parser/html/nsHtml5TreeBuilder.cpp
+++ b/parser/html/nsHtml5TreeBuilder.cpp
@@ -3301,17 +3301,17 @@ nsHtml5TreeBuilder::findLastInTableScope
   return NS_HTML5TREE_BUILDER_NOT_FOUND_ON_STACK;
 }
 
 void 
 nsHtml5TreeBuilder::clearStackBackTo(int32_t eltPos)
 {
   int32_t eltGroup = stack[eltPos]->getGroup();
   while (currentPtr > eltPos) {
-    if (stack[currentPtr]->ns == kNameSpaceID_XHTML && stack[currentPtr]->getGroup() == NS_HTML5TREE_BUILDER_TEMPLATE && (eltGroup == NS_HTML5TREE_BUILDER_TABLE || eltGroup == NS_HTML5TREE_BUILDER_TBODY_OR_THEAD_OR_TFOOT || eltGroup == NS_HTML5TREE_BUILDER_TR || eltGroup == NS_HTML5TREE_BUILDER_HTML)) {
+    if (stack[currentPtr]->ns == kNameSpaceID_XHTML && stack[currentPtr]->getGroup() == NS_HTML5TREE_BUILDER_TEMPLATE && (eltGroup == NS_HTML5TREE_BUILDER_TABLE || eltGroup == NS_HTML5TREE_BUILDER_TBODY_OR_THEAD_OR_TFOOT || eltGroup == NS_HTML5TREE_BUILDER_TR || !eltPos)) {
       return;
     }
     pop();
   }
 }
 
 void 
 nsHtml5TreeBuilder::resetTheInsertionMode()

